package ru.ifmo.thesis.suite;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import ru.ifmo.thesis.domain.Job;
import ru.ifmo.thesis.domain.Location;
import ru.ifmo.thesis.domain.Shedule;
import ru.ifmo.thesis.domain.Worker;
import ru.ifmo.thesis.event.Event;
import ru.ifmo.thesis.event.EventListener;
import ru.ifmo.thesis.suite.SuiteRunner.NextGenerationEvolved;
import ru.ifmo.thesis.suite.SuiteRunner.TaskFinishedEvent;
import ru.ifmo.thesis.suite.SuiteRunner.TaskStartedEvent;
import ru.ifmo.thesis.util.SequenceGeneratortor;

public class MyLogger implements SuiteRunnerLogger {

	
	
	public class MyListener implements EventListener {

		@Override
		public void fireEvent(Event event) {
			TaskFinishedEvent e = (TaskFinishedEvent) event;
			Shedule s = e.getShedule();
			
			SequenceGeneratortor rowIndex = new SequenceGeneratortor(0);
			
			List<Worker> wl = new ArrayList(s.getWorkers());
			for (int workerIndex = 0; workerIndex < wl.size(); workerIndex++) {
				Worker w = wl.get(workerIndex);
				List<Job> personalShedule = s.getPersonalShedule(w);
				for (int j = 0; j < personalShedule.size(); j++) {
					SequenceGeneratortor cellIndex = new SequenceGeneratortor(0);

					Job job = personalShedule.get(j);
					Location loc = job.getLocation();
					
					Row row = sheet.createRow(rowIndex.nextValue());
					
					Cell workerCell = row.createCell(0);
					Cell xCell = row.createCell(1);
					Cell yCell = row.createCell(2);

					workerCell.setCellValue(workerIndex);
					xCell.setCellValue(loc.getLatitude());
					yCell.setCellValue(loc.getLongtitude());
				}
			}
			
		}

	}
	
	private final StringBuilder sb = new StringBuilder();
	
	private final String fileName;

	private XSSFWorkbook workbook;

	private Sheet sheet;
	
	public MyLogger(String fileName, SuiteRunner runner) {
		super();
		this.fileName = fileName;

		this.workbook = new XSSFWorkbook();
		this.sheet = workbook.createSheet("main");

		runner.addEventListener(SuiteRunner.TaskFinishedEvent.NAME, new MyListener());
	}



	@Override
	public void close() throws IOException {
		FileOutputStream results = new FileOutputStream(fileName);
		workbook.write(results);
		results.close();

	}

}
